package manager.database;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DatabaseSqlSession{
	private static SqlSessionFactory sqlSessionFactory;
	private static final String resource = "mybatis.xml";//mybatis的配置文件
	private static ThreadLocal<SqlSession> tl=new ThreadLocal<SqlSession>();
	static{
		//方法一:使用MyBatis提供的Resources类加载mybatis的配置文件（它也加载关联的映射文件）
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream(resource);
			//构建sqlSession的工厂
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//*方法二:使用类加载器加载mybatis的配置文件（它也加载关联的映射文件）
        //InputStream inputStream = DatabaseSqlSession.class.getClassLoader().getResourceAsStream(resource); 
	}
	private DatabaseSqlSession() throws Exception{
			
	}
	//SqlSession不能使用单例,sqlSessionFactory可以使用单例
	public static SqlSession getSqlSession(){
		SqlSession sqlSession=tl.get();
		if(sqlSession==null){
			sqlSession=sqlSessionFactory.openSession();
			tl.set(sqlSession);
		}
		return sqlSession;
	}
	
	public static void closeSqlSession(){
		SqlSession sqlSession=tl.get();
		if (sqlSession !=null) {
			tl.set(null);
			sqlSession.close();
		}
	}
	
	public static void commit(){
		SqlSession sqlSession=tl.get();
		if (sqlSession !=null) {
			tl.set(null);
			sqlSession.commit();
		}
	}
	
	public static void rollBack(){
		SqlSession sqlSession=tl.get();
		if (sqlSession !=null) {
			tl.set(null);
			sqlSession.rollback();
		}
	}
	
}
